package com.iscreen.dbupgrade.commands;

import org.apache.log4j.Logger;

import com.iscreen.dbupgrade.SchemaUtils;
import com.iscreen.dbupgrade.objects.Command;
import com.iscreen.dbupgrade.operations.UpgradeCommand;
import com.iscreen.dbupgrade.operations.UpgradeStep;
import com.iscreen.dbupgrade.queries.CreateTableQuery;
import com.iscreen.dbupgrade.queries.UpgradeQuery;
import com.iscreen.utils.db.query.Query;
import com.iscreen.utils.exceptions.IScreenException;

public class CreateTableCommand extends UpgradeCommand
{
	private Logger logger = Logger.getLogger(CreateTableQuery.class);

	
	public CreateTableCommand(Command command, UpgradeStep parentStep)
	{
		super(command, parentStep);
	}

	@Override
	protected UpgradeQuery getUpgradeQuery(Command command)
	{
		return queryFactory.createCreateTableQuery(command.getCreateTable());
	}
	
	private void executeQuery(String tableName) throws IScreenException
	{
		Query query = connection.createQuery(upgradeQuery.getSql());
		try
		{
			query.execute();
		}
		finally
		{
			query.close();
		}

		logger.info("Table " + tableName + " created.");
	}

	@Override
	protected void doExecute() throws IScreenException
	{
		String tableName = ((CreateTableQuery) upgradeQuery).getTableName();
		if (SchemaUtils.isTableExists(connection, tableName))
		{
			logger.info("Table " + tableName
					+ " not created. Table already exists.");
			return;
		}

		executeQuery(tableName);
	}

	@Override
	public String getOperation()
	{
		return "Create table "
				+ ((CreateTableQuery) upgradeQuery).getTableName();
	}
}
